package com.android.qjpmc.application_module.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.android.qjpmc.R;
import com.android.qjpmc.bean.GroupPointHisListBean;
import com.android.qjpmc.bean.PointTimeDataBean;
import com.android.qjpmc.databinding.ViewHisCurveLinechartBinding;
import com.android.qjpmc.widget.base.BaseCustomView;
import com.android.qjpmc.widget.utils.TimeUtils;
import com.android.qjpmc.widget.utils.UIUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.renderer.XAxisRenderer;
import com.github.mikephil.charting.utils.MPPointF;
import com.github.mikephil.charting.utils.Transformer;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.orhanobut.logger.Logger;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import androidx.viewpager.widget.ViewPager;

public class HisCurveLineChartView extends BaseCustomView<ViewHisCurveLinechartBinding> {

    private ArrayList<String> xAxisTimeList;
    private LineData lineData;
    //0是历史数据 1是实时曲线数据
    private int fromType;

    public HisCurveLineChartView(Context context) {
        super(context);
    }

    public HisCurveLineChartView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_his_curve_linechart;
    }

    @Override
    protected void initView(Context context, AttributeSet attrs) {

    }

    @Override
    public void initData(Context context) {

    }

    @Override
    public void initEvent(Context context) {
        handleTouchConflict();
    }

    public void handleTouchConflict() {
        mBinding.chart.setOnTouchListener(new View.OnTouchListener() {
            private float lastX;
            PointF downPoint = new PointF();

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        lastX = event.getX();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (Math.abs(event.getX() - lastX) > 15) {
                            // 如果发生了横向滑动，则禁用ViewPager的滑动操作
                            mBinding.chart.getParent().requestDisallowInterceptTouchEvent(true);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        mBinding.chart.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
                return false;
            }
        });

    }

    public static final SimpleDateFormat DEFAULT_MOUTH_DAY = new SimpleDateFormat("MM-dd\nHH:mm", Locale.getDefault());
    public static final SimpleDateFormat DEFAULT_MOUTH_SS = new SimpleDateFormat("dd-HH\nmm:ss", Locale.getDefault());

    public void setFromType(int fromType) {
        this.fromType = fromType;
    }

    //初始化曲线控件
    public void initializeChart(String title, List<PointTimeDataBean> pointValueList) {
        //  mBinding.tvTitle.setText(companyName + groupPointHisListBean.deviceName + groupPointHisListBean.propsName);
        mBinding.tvTitle.setText(title);

        // *************************数据转换********************* //
        LineChart lineChart = mBinding.chart;
        //数据集合
        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
        //X轴坐标..........
        xAxisTimeList = new ArrayList<>();
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < pointValueList.size(); i++) {
            PointTimeDataBean pointTimeDataBean = pointValueList.get(i);
            xAxisTimeList.add(pointTimeDataBean.startTime);
            entries.add(new Entry(i, (float) pointTimeDataBean.value));
        }

        //第一条曲线数据

        LineDataSet dataSet = new LineDataSet(entries, "");
        dataSet.setColors(UIUtils.getColor(R.color.gray_f7)); // 每个点之间线的颜色，还有其他几个方法，自己看
        //加入数据队列集
        dataSets.add(dataSet);

        dataSet.setDrawValues(true);
        dataSet.setValueTextColor(UIUtils.getColor(R.color.black_33));
        lineData = new LineData(dataSets);

        lineChart.setData(lineData);
        initLineDataSet(dataSet, R.color.buttonColor, LineDataSet.Mode.CUBIC_BEZIER);

        /***图表设置***/
        //是否展示网格线
        lineChart.setDrawGridBackground(false);
        //是否显示边界
        lineChart.setDrawBorders(false);
        //是否可以拖动
        lineChart.setDragEnabled(true);
        //是否有触摸事件
        lineChart.setTouchEnabled(true);
        //设置XY轴动画效果
        lineChart.animateY(300);
        lineChart.animateX(300);
        lineChart.setScaleEnabled(true);
        //一屏最大显示点数
        lineChart.setVisibleXRangeMaximum(5);
        lineChart.getDescription().setEnabled(false);
        /***XY轴的设置***/
        //隐藏右侧Y轴坐标
        lineChart.getAxisRight().setEnabled(false);
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setTextSize(10);
        //由于显示时间长度很长 X轴处理换行
        lineChart.setExtraBottomOffset(2 * 10);
        lineChart.setXAxisRenderer(new CustomXAxisRenderer(lineChart.getViewPortHandler(), lineChart.getXAxis(), lineChart.getTransformer(YAxis.AxisDependency.LEFT)));

        YAxis leftYAxis = lineChart.getAxisLeft();
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0);
        xAxis.setGranularity(1f);
        //xAxis.setAxisMaximum(4);//设置x轴的最大刻度
        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);

        xAxis.setValueFormatter(new ValueFormatter() {//x 轴自定义标签的设置
            @Override
            public String getFormattedValue(float value) {
                if (value < 0 || value >= xAxisTimeList.size()) {
                    return "";
                }
                String time = xAxisTimeList.get((int) value);
                long longTime = TimeUtils.parsDataTimeLong(time, TimeUtils.DEFAULT_SDF);
                if (fromType == 1) {
                    return TimeUtils.parseTimeLong(longTime / 1000, DEFAULT_MOUTH_SS);
                } else {
                    return TimeUtils.parseTimeLong(longTime / 1000, DEFAULT_MOUTH_DAY);

                }
                //return "11\n12";
            }
        });
        dataSet.setValueFormatter(new ValueFormatter() {//x 轴自定义标签的设置
            @Override
            public String getFormattedValue(float value) {
                return String.format("%.1f", value);
            }
        });
        lineChart.getLegend().setEnabled(false);
        // Y轴更多属性
        //dataSet.setAxisDependency(YAxis.AxisDependency.LEFT);  // 设置dataSet应绘制在Y轴的左轴还是右轴，默认LEFT
        leftYAxis.setDrawZeroLine(false);    // 绘制值为0的轴，默认false,其实比较有用的就是在柱形图，当有负数时，显示在0轴以下，其他的图这个可能会看到一些奇葩的效果
        leftYAxis.setZeroLineWidth(10);  // 0轴宽度
        leftYAxis.setZeroLineColor(Color.BLUE);   // 0轴颜色
        // 轴值转换显示
    }

    private void initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(3f);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(true);
        lineDataSet.setValueTextSize(10f);
        //设置折线图填充
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFormLineWidth(1f);
        lineDataSet.setFormSize(15.f);
        //设置曲线展示为圆滑曲线（如果不设置则默认折线）
        lineDataSet.setMode(mode);
    }

    public void notifyChartView(List<PointTimeDataBean> pointValueList) {
        if (xAxisTimeList.size() >= 5) {
            //重新设置可以滑动
            mBinding.chart.setVisibleXRangeMaximum(5);
        }
        for (int i = 0; i < pointValueList.size(); i++) {
            PointTimeDataBean pointTimeDataBean = pointValueList.get(i);
            xAxisTimeList.add(xAxisTimeList.size() - 1, pointTimeDataBean.startTime);
            Entry entry = new Entry(lineData.getEntryCount(), (float) pointTimeDataBean.value); // 创建一个点
            lineData.addEntry(entry, 0); // 将entry添加到指定索引处的曲线中

        }
        mBinding.chart.notifyDataSetChanged();
        mBinding.chart.moveViewToX(xAxisTimeList.size() - 4);
        mBinding.chart.invalidate();
    }


    public class CustomXAxisRenderer extends XAxisRenderer {
        public CustomXAxisRenderer(ViewPortHandler viewPortHandler, XAxis xAxis, Transformer trans) {
            super(viewPortHandler, xAxis, trans);
        }

        @Override
        protected void drawLabel(Canvas c, String formattedLabel, float x, float y, MPPointF anchor, float angleDegrees) {
            String line[] = formattedLabel.split("\n");
            if (line.length <= 1) {
                Utils.drawXAxisValue(c, line[0], x, y, mAxisLabelPaint, anchor, angleDegrees);
            } else {
                Utils.drawXAxisValue(c, line[0], x, y, mAxisLabelPaint, anchor, angleDegrees);
                Utils.drawXAxisValue(c, line[1], x, y + mAxisLabelPaint.getTextSize(), mAxisLabelPaint, anchor, angleDegrees);
            }
        }
    }
}
